<?php
/**
 * Created by PhpStorm.
 * User: Xiaowei Liang
 * Date: 2017-09-01
 * Time: 15:26
 */

namespace App\Http\Controllers\Api\Common;


use App\Http\Controllers\Controller;
use App\Libs\Contracts\Orc\AipOcr;
use App\Libs\Contracts\PayMent\Wxpay\H5NativePay;
use App\Libs\Contracts\PayMent\Wxpay\NativePay;
use App\Libs\Contracts\PayMent\Wxpay\Refund;
use App\Libs\Contracts\PayMent\Wxpay\ScanNativePay;
use App\Libs\Contracts\Push\Jpush\JpushServer;
use App\Libs\Contracts\Qrcode\QRencode;
use App\Libs\Contracts\SMS\QQSmsSDK;
use App\Libs\httpUtil;
use App\Libs\OSS;
use App\Libs\Sms\AliSms;
use App\Libs\STS;
use App\Models\AllCity;
use App\Models\City;
use App\Models\District;
use App\Models\Logistics;
use App\Models\SystemSetting;
use App\Models\User;
use App\Services\Ali\AliService;
use Darabonba\OpenApi\Models\Config;
use Doctrine\DBAL\Driver\IBMDB2\DB2Driver;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redis;

class CommonController extends Controller
{
    public function jijinEmail(Request $request)
    {
        $content = $request->all();
        $string = null;
        foreach ($content as $key => $value) {
            $string .= $key . ":" . $value . "\n";
        }
        Mail::raw($string, function ($message) {
            //$message->to('1821786397@qq.com')->subject('以下内容为本次所接参数');
            $message->to('info@angelspace.group')->subject('以下内容为本次所接参数');
        });
        return $this->apiResponse(true);
    }

    public function getMZUrl(Request $request)
    {
        $token = new \App\Services\Front\WxService();
        $access_token = $token->getMZAccessToken();
        $url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=$access_token";
        $body = [
            'jump_wxa' => (object)[
                'path' => "pages/index/index",
                //'query' => "id=$id"
            ],
            'expire_type' => 1,
            'expire_interval' => 30
        ];
        $http = new httpUtil();
        $res = $http->request($url, $body);
        if ($res['errcode']) {
            return $this->apiResponse('', config('errorLiu.SHENGCHENGWAILOAINSHNIB'));
        }
        $url = $res['openlink'];
        return $this->apiResponse($url);
    }
    public function antestEmail(Request $request)
    {
        $content = $request->all();
        $string = null;
        foreach ($content as $key => $value) {
            $string .= $key . ":" . $value . "\n";
        }
        Mail::raw($string, function ($message) {
            //$message->to('1821786397@qq.com')->subject('以下内容为本次所接参数');
            $message->to('support@anbio-order.com')->subject('以下内容为本次所接参数');
        });
        return $this->apiResponse(true);
    }

    public function anbioEmail(Request $request)
    {
        $content = $request->all();
        $string = null;
        foreach ($content as $key => $value) {
            $string .= $key . ":" . $value . "\n";
        }
        Mail::raw($string, function ($message) {
            //$message->to('1821786397@qq.com')->subject('以下内容为本次所接参数');
            $message->to('jerry_cheung@anbio.com')->subject('以下内容为本次所接参数');
        });
        return $this->apiResponse(true);
    }

    public function ossUpload(Request $request)
    {
        $file = $request->file('file');
        if ($file->isValid()) {
            $fileSize = $file->getSize();
//            if($fileSize > 2097152){
//                $USERID = $request->USERID;
//                return $this->apiResponse($USERID,'',config('errorCode.FILE_BIG_SIZE'));
//            }
            $realPath = $file->getRealPath();
            $entension = $file->getClientOriginalExtension();
            $clientName = $file->getClientOriginalName();    //客户端文件名称
            $newName = 'uploads/' . md5(date('ymdhis') . $clientName) . "." . $entension;    //定义上传文件的新名称

            $mimeTye = $file->getMimeType();
            $path = $newName;
            $model = new OSS();

            $result = $model->publicUpload('upload-file-image-admin', $path, $realPath, ['ContentType' => $mimeTye]);
            if ($result) {
                $data = $model->url . '/' . $newName;
                return $this->apiResponse($data, "上传文件成功");
            }
        }
        return $this->apiResponse('', '上传文件失败', 10000);
    }

    public function district()
    {
        $districtList = AllCity::select()->first();
        return $this->apiResponse(json_decode($districtList['text']));
    }

    public function checkStatus()
    {
        $s = SystemSetting::find(1);
        if ($s['checkStatus']) {
            return $this->apiResponse(true);
        } else {
            return $this->apiResponse(false);
        }
    }
    function kuaidi(Request $request)
    {
        $com = $request->wuliu_code;
        $num = $request->wuliu_num;
        $key = 'jcOqojpa620';                        //客户授权key
        $customer = '29A40FC666F0B24441D3D8EFDC919731';//查询公司编号
        $param = array(
            'com' => $com,             //快递公司编码
            'num' => $num,     //快递单号
            'phone' => '',                //手机号
            'from' => '',                 //出发地城市
            'to' => '',                   //目的地城市
            'resultv2' => '1'             //开启行政区域解析
        );

        //请求参数
        $post_data = array();
        $post_data["customer"] = $customer;
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"] . $key . $post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);

        $url = 'http://poll.kuaidi100.com/poll/query.do';    //实时查询请求地址

        $params = "";
        foreach ($post_data as $k => $v) {
            $params .= "$k=" . urlencode($v) . "&";              //默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);
// echo '请求参数<br/>'.$post_data;
        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data = str_replace("\"", '"', $result);
        $data = json_decode($data);
        return $this->apiResponse($data);
        // echo '<br/><br/>返回数据<br/>';
        // dump($data);
    }

//    public function kuaidi(Request $request)
//    {
//        $name = $request->name;
//        $code = $request->code;
//        $data = app("kuaidi")->getData($name, $code);
//        if (!isset($data['data'])) {
//            return $this->apiResponse('', config('errorCode.KUAIDI_FAILS'));
//        }
//        $ftime = array_column($data['data'], 'ftime');
//        array_multisort($ftime, SORT_DESC, $data['data']);
//        return $this->apiResponse($data, "获取快递成功");
//    }


    /**
     * 通过手机号获取验证码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function code(Request $request)
    {
        $phone = $request->phone;
        if (!$phone) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $code = rand(10000, 99999);
        $status = app('sms')->send($phone, $code);
        if ($status == 100) {
            return $this->apiResponse('成功');
        } else {
            return $this->apiResponse('', config('errorCode.CODE_FAILS'));
        }
    }

    /**
     * 身份证识别
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function idcard(Request $request)
    {
        $certificatesNumber = $request->certificatesNumber;
        $certificatesPositive = $request->certificatesPositive;
        /* if(!$certificatesNumber || !$certificatesPositive){
             return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
         }*/
        $wxService = new AliService();
        $url = $wxService->getFilePath($certificatesPositive);
        $aipOcr = new AipOcr(env("BAIDU_APPID"), env("BAIDU_API_KEY"), env("BAIDU_SECRET_KEY"));
        $data = $aipOcr->idcard(file_get_contents($url), true);
        if (!empty($data['error_code'])) {
            return $this->apiResponse('', config('errorCode.CARD_NO'));
        }
        $result['certificatesNumber'] = $data['words_result']['公民身份号码']['words'];
        $result['userName'] = $data['words_result']['姓名']['words'];
        $result['birthday'] = date("Y-m-d", strtotime($data['words_result']['出生']['words']));
        $result['sex'] = str_replace(array("男", "女"), array('1', '2'), $data['words_result']['性别']['words']);
        $result['nation'] = $data['words_result']['民族']['words'];
        return $this->apiResponse($result);
        /*$cards = $data['words_result']['公民身份号码']['words'];
        if($cards != $certificatesNumber){
            return $this->apiResponse('', config('errorCode.CARD_ERROR'));
        }*/
    }

    public function cityImport()
    {
        $url = "http://apis.juhe.cn/simpleWeather/cityList?key=65eeadafaee551ac108b29bb79495705";
        $http = new httpUtil();
        $result = $http->http_get($url);
        $data = json_decode($result, true);
        $city = $data['result'];
        City::insert($city);
        return $this->apiResponse(true);
    }

    public function weather(Request $request)
    {
        $lat = $request->lat;//纬度
        $lng = $request->lng;//经度

        $url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=6LM5eq2upWz1oXONuzkhj6VFljEcKuXw&output=json&coordtype=wgs84ll&location=$lat,$lng";
        $http = new httpUtil();
        $result = $http->http_get($url);
        $data = json_decode($result, true);
        $flag = false;
        $id = 0;
        if ($data) {
            if ($data['status'] == 0) {
                $province = $data['result']['addressComponent']['province'];
                $city = $data['result']['addressComponent']['city'];
                $district = $data['result']['addressComponent']['district'];
                $province = explode("省", $province);
                $province = explode("市", $province[0]);
                $province = $province[0];
                $city = explode("市", $city);
                $city = $city[0];
                $district = explode("县", $district);
                $district = $district[0];
                $status = City::where(['province' => $province, 'city' => $city, 'district' => $district])->first();
                if ($status) {
                    $id = $status['id'];
                } else {
                    $id = $city;
                }
                $url = "http://apis.juhe.cn/simpleWeather/query?key=65eeadafaee551ac108b29bb79495705&city=" . $district;
                $http = new httpUtil();
                $result = $http->http_get($url);
                $data = json_decode($result, true);
                $res['province'] = $province;
                $res['city'] = $city;
                $res['district'] = $district;

                if ($data['error_code'] == 0) {
                    $weather = $data['result']['realtime']['info'];//天气
                    $temperature = $data['result']['realtime']['temperature'];//温度
                    $humidity = $data['result']['realtime']['humidity'];//湿度
                    $future = $data['result']['future'][0]['temperature'];//温度范围
                    $future = explode("/", $future);
                    $temp = explode("℃", $future[1]);
                    $lowTemperature = $future[0];
                    $highTemperature = $temp[0];
                    $res['lowTemperature'] = $lowTemperature;
                    $res['highTemperature'] = $highTemperature;
                    $res['weather'] = $weather;
                    $res['temperature'] = $temperature;
                    $res['humidity'] = $humidity;
                    $flag = true;
                } else {
                    $url = "http://apis.juhe.cn/simpleWeather/query?key=65eeadafaee551ac108b29bb79495705&city=" . $id;
                    $http = new httpUtil();
                    $result = $http->http_get($url);
                    $data = json_decode($result, true);
                    if ($data['error_code'] == 0) {
                        $weather = $data['result']['realtime']['info'];//天气
                        $temperature = $data['result']['realtime']['temperature'];//温度
                        $humidity = $data['result']['realtime']['humidity'];//湿度
                        $future = $data['result']['future'][0]['temperature'];//温度范围
                        $future = explode("/", $future);
                        $temp = explode("℃", $future[1]);
                        $lowTemperature = $future[0];
                        $highTemperature = $temp[0];
                        $res['lowTemperature'] = $lowTemperature;
                        $res['highTemperature'] = $highTemperature;
                        $res['weather'] = $weather;
                        $res['temperature'] = $temperature;
                        $res['humidity'] = $humidity;
                        $flag = true;
                    }
                }
            }
        }
        $url = "http://apis.juhe.cn/simpleWeather/wids?key=65eeadafaee551ac108b29bb79495705";
        $http = new httpUtil();
        $result = $http->http_get($url);
        $data = json_decode($result, true);
        $res['weatherList'] = $data['result'];
        if ($flag) {
            return $this->apiResponse($res);
        } else {
            return $this->apiResponse('', config("errorCode.SERVER_EXCEPTION"));
        }

    }

    public function uuid(Request $request)
    {
        $uuid = $request->uuid;
        if (!$uuid) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $status = \App\Models\Uuid::where('uuid', $uuid)->first();
        if (!$status) {
            \App\Models\Uuid::create(['uuid' => $uuid]);
        }
        return $this->apiResponse(true);
    }

    //阿里云获取授权
    public function getAccess()
    {
        $sts = new STS();
        $data = $sts->sts();
        $data['region'] = "oss-cn-shenzhen";
        $data['bucket'] = "30days";
        $data['url'] = "https://30days.oss-cn-shenzhen.aliyuncs.com";
        return $this->apiResponse($data);
    }
}